package com.truthbean.jeetb.api.websocket;

import com.truthbean.jeetb.api.websocket.handler.MessageSessionHandler;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Time;
import java.util.Date;

/**
 * Created by TruthBean on 2016-10-17 17:38.
 */
@ApplicationScoped
@ServerEndpoint("/WeChat")
public class MessageWebSocketServer implements Serializable {
    @Inject
    private MessageSessionHandler sessionHandler;

    @OnOpen
    public void open(Session session) {
        System.out.println("webSocket open by " + session.getId());
        try {
            session.getBasicRemote().sendText("hello from remote");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void close(Session session) {
        System.out.println("webSocket close by " + session.getId());
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

    @OnMessage
    public void handleMessage(String message, Session session) {
        System.out.println("message from client " + session.getId() + " : " + message);
        try {
            session.getBasicRemote().sendText("sorry, I'm just a echo machine.  " + new Time(System.currentTimeMillis()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
